package com.lin.mr.maizilaundry.fragmentcloth;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.lin.mr.maizilaundry.R;
import com.lin.mr.maizilaundry.myapplication.MyApplication;

/**
 * 本页的动画可分为两个部分：两扇门和标题。为了保证动画的同步，使用AnimatorSet来同步触发。
 */
public class FragmentAnimation extends Fragment {
    private ImageView imageLeft,imageRight;
    private TextView textView;
    private AnimatorSet animSet;
    private View view;
    private boolean isCreateView;//判断onCreateView方法是否调用

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        isCreateView = true;
        initView();
        return view;
    }

    private void initView(){
        view = View.inflate(MyApplication.getContext(),R.layout.fragment_animation,null);
        imageLeft = (ImageView) view.findViewById(R.id.left_part);
        imageRight = (ImageView) view.findViewById(R.id.right_part);
        textView = (TextView) view.findViewById(R.id.textView);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        if (isVisibleToUser){
            if (isCreateView == false){
                initView();
            }
            startAnimation();
        }
    }

    private void startAnimation() {
        Log.e("anima","startAnimation调用");
        animSet = new AnimatorSet();
        /**
         * 两扇门的动画
         */
        //向左移动的图片
        ObjectAnimator toLeft =ObjectAnimator.ofFloat(imageLeft,"translationX", 0f ,-500f);
        toLeft.setDuration(2000);
//        toLeft.start();
        //向右移动的图片
        ObjectAnimator toRight = ObjectAnimator.ofFloat(imageRight,"translationX", 0 ,500f);
        toRight.setDuration(2000);
//        toRight.start();
        animSet.play(toLeft).with(toRight);

        /**
         * 标题的动画
         */
        //放大
        ObjectAnimator textEnlargeX = ObjectAnimator.ofFloat(textView,"scaleX",1f,3f);
        textEnlargeX.setDuration(2000);
        ObjectAnimator textEnlargeY = ObjectAnimator.ofFloat(textView,"scaleY",1f,3f);
        textEnlargeY.setDuration(2000);
        //渐变（透明）
        ObjectAnimator textAlpha = ObjectAnimator.ofFloat(textView,"alpha",1f,0f);
        textAlpha.setDuration(2000);
        //同时执行放大和渐变动画
        animSet.play(textEnlargeX).with(textEnlargeY).with(textAlpha);
        animSet.setDuration(2000);
        animSet.start();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isCreateView = false;
    }
}
